package cn.zlg.www.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;


import com.sany.canwifi.R;

import cn.zlg.www.main.MainActivity;
import cn.zlg.www.main.SetInfo;
import cn.zlg.www.view.IpAlertDialog;
import cn.zlg.www.view.PortAlertDialog;

public class SetFragment extends Fragment {
    public static final String TAG = "SetFragment";
    private TextView mLocalPortTextView, mIpAddrTextView, mPortTextView;
    private MainActivity mActivity;
    private View mView;
    private int mType = MainActivity.TYPE_TCP_CLIENT;
    private SetInfo mSetInfo;
    private boolean mConnected = false;
    private boolean mCreated = false;

    private RelativeLayout mTransLayout, mPlayerLayout;
    private RelativeLayout mConnLayout, mLocalPortLayout, mIpAddrLayout,
            mWorkPortLayout, mErrPortLayout;
    private TextView mTransTextView, mPlayerTextView, mConnecTextView,
            mErrTextView;
    private TextView mIpTextViewLeft;
    private LayoutOnClickListener mLayoutOnClickListener;
    private IpAlertDialog mIpAlertDialog;
    private PortAlertDialog mPortAlertDialog;

    private int mLocalPort = 6001;
    private String mIpAddr = "192.168.0.178";
    private int mWorkPort = 4001;
    private int mErrPort = 5001;

    private static final String SETINFONAME = "setinfo";
    private static final String LOCALPORT = "localport";
    private static final String IPADDRESS = "ipaddress";
    private static final String WORKPORT = "workport";
    private static final String CONNTYPE = "conntype";
    private static final String ERRPORT = "errport";
    private SharedPreferences mSharedPreferences;

    private static final int CNN_CONNECT = 0;
    private static final int CNN_UNCONNECT = 1;
    private CnnHandler mCnnHandler;

    private long mTimeCount;

    public SetFragment() {
        super();
        mSetInfo = new SetInfo();
        mCnnHandler = new CnnHandler();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = (MainActivity) getActivity();
        mView = inflater.inflate(R.layout.setting, null);

        return mView;
    }

    private void setAllWidgetInvisible() {
        mLocalPortTextView.setEnabled(false);
        mIpAddrTextView.setEnabled(false);
        mPortTextView.setEnabled(false);
        mTransLayout.setClickable(false);
        mPlayerLayout.setClickable(false);
        mLocalPortLayout.setClickable(false);
        mIpAddrLayout.setClickable(false);
        mWorkPortLayout.setClickable(false);
        mErrPortLayout.setClickable(false);
        mErrTextView.setEnabled(false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        mLayoutOnClickListener = new LayoutOnClickListener();
        mTransLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayouttrans);
        mTransLayout.setOnClickListener(mLayoutOnClickListener);
        mPlayerLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutplay);
        mPlayerLayout.setOnClickListener(mLayoutOnClickListener);
        mConnLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutconnect);
        mConnLayout.setOnClickListener(mLayoutOnClickListener);
        mErrPortLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutErrPort);
        mErrPortLayout.setOnClickListener(mLayoutOnClickListener);
        mLocalPortLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutlocalport);
        mLocalPortLayout.setOnClickListener(mLayoutOnClickListener);
        mIpAddrLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutip);
        mIpAddrLayout.setOnClickListener(mLayoutOnClickListener);
        mWorkPortLayout = (RelativeLayout) mView
                .findViewById(R.id.RelativeLayoutworkport);
        mWorkPortLayout.setOnClickListener(mLayoutOnClickListener);

        mTransTextView = (TextView) mView.findViewById(R.id.textViewtrans);
        mPlayerTextView = (TextView) mView.findViewById(R.id.textViewplayer);
        mErrTextView = (TextView) mView.findViewById(R.id.textViewErrPort);
        mLocalPortTextView = (TextView) mView
                .findViewById(R.id.textViewlocalport);
        mIpAddrTextView = (TextView) mView.findViewById(R.id.textViewipaddr);
        mPortTextView = (TextView) mView.findViewById(R.id.textViewworkport);
        mIpTextViewLeft = (TextView) mView
                .findViewById(R.id.textViewipaddrleft);

        mConnecTextView = (TextView) mView.findViewById(R.id.textViewConnect);
        mConnecTextView.setText(mConnected ? "断开" : "连接");
        restoreViewStatus();
        if (mConnected) {
            setAllWidgetInvisible();
        }
        mTransTextView.setText(MainActivity.TYPE_UDP == mType ? "UDP" : "TCP");
        mPlayerTextView.setText(MainActivity.TYPE_TCP_CLIENT == mType ? "客户端"
                : "服务器端");
        mLocalPortTextView.setText(mLocalPort + "");
        mIpAddrTextView.setText(mIpAddr);
        mPortTextView.setText(mWorkPort + "");
        mErrTextView.setText(mErrPort + "");

        if (!mCreated) {
            restoreSetInfo();
            mCreated = true;
        }
    }

    public void setSureButtonFlag(boolean bCnned) {
        if (mConnecTextView != null) {
            mConnected = bCnned;
            mConnecTextView.setTextColor(mActivity.getResources().getColor(
                    R.color.black));
            mConnLayout.setClickable(true);
            if (mConnected) {
                setAllWidgetInvisible();
                mConnecTextView.setText("断开");
            } else {
                restoreViewStatus();
                mConnecTextView.setText("连接");
            }
        }
    }

    void connect() {
        saveSetInfo();
        mSetInfo.nLocalPort = mLocalPort;
        mSetInfo.ipAddress = mIpAddr;
        mSetInfo.nWorkPort = mWorkPort;
        mSetInfo.nPortErrNotice = mErrPort;

        if (MainActivity.TYPE_TCP_SERVER == mType && mSetInfo.nLocalPort == 0) {
            Toast toast = Toast.makeText(mActivity, "端口为0，请输入端口值", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (mType == MainActivity.TYPE_TCP_CLIENT
                && (mSetInfo.ipAddress.equals("") || mSetInfo.nWorkPort == 0)) {
            Toast toast = Toast.makeText(mActivity, "端口或IP为0，请输入端口值", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (mType == MainActivity.TYPE_UDP
                && (mSetInfo.nLocalPort == 0 || mSetInfo.ipAddress.equals("") || mSetInfo.nWorkPort == 0)) {
            Toast toast = Toast.makeText(mActivity, "端口或IP为0，请输入端口值", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        String log1 = mSetInfo.nLocalPort + ":" + mSetInfo.ipAddress + ":" + mSetInfo.nWorkPort + ":" + mSetInfo.nPortErrNotice;
        System.out.println(log1);
        Log.e(TAG, "connect: " + log1);
        try {
            mActivity.doCommand(mType, mSetInfo);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void unconnect() {
        try {
            mActivity.doCommand(MainActivity.TYPE_UNCONNECT, null);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void saveSetInfo() {
        mSharedPreferences = mActivity.getSharedPreferences(SETINFONAME,
                Context.MODE_PRIVATE);
        Editor editor = mSharedPreferences.edit();
        editor.putInt(LOCALPORT, mLocalPort);
        editor.putString(IPADDRESS, mIpAddr);
        editor.putInt(WORKPORT, mWorkPort);
        editor.putInt(CONNTYPE, mType);
        editor.putInt(ERRPORT, mErrPort);
        editor.commit();
    }

    public void restoreSetInfo() {
        mSharedPreferences = mActivity.getSharedPreferences(SETINFONAME,
                Context.MODE_PRIVATE);
        mLocalPort = mSharedPreferences.getInt(LOCALPORT, mLocalPort);
        mIpAddr = mSharedPreferences.getString(IPADDRESS, mIpAddr);
        mWorkPort = mSharedPreferences.getInt(WORKPORT, mWorkPort);
        mErrPort = mSharedPreferences.getInt(ERRPORT, mErrPort);
        mLocalPortTextView.setText("" + mLocalPort);
        mIpAddrTextView.setText(mIpAddr);
        mPortTextView.setText("" + mWorkPort);
        mErrTextView.setText("" + mErrPort);
        int nType = mSharedPreferences.getInt(CONNTYPE,
                MainActivity.TYPE_TCP_CLIENT);
        if (MainActivity.TYPE_TCP_SERVER == nType) {
            showTcpServerView();
        } else if (MainActivity.TYPE_TCP_CLIENT == nType) {
            showTcpClientView();
        } else {
            showUdpView();
        }
    }

    void restoreViewStatus() {
        if (MainActivity.TYPE_TCP_SERVER == mType) {
            showTcpServerView();
        } else if (MainActivity.TYPE_TCP_CLIENT == mType) {
            showTcpClientView();
        } else {
            showUdpView();
        }
    }

    private void showTcpServerView() {
        setAllWidgetInvisible();
        mErrPortLayout.setClickable(true);
        mErrTextView.setEnabled(true);
        mLocalPortLayout.setVisibility(View.VISIBLE);
        mWorkPortLayout.setVisibility(View.GONE);
        mIpTextViewLeft.setText("错误通知IP地址");
        mLocalPortTextView.setEnabled(true);
        mPlayerLayout.setVisibility(View.VISIBLE);
        mPlayerLayout.setClickable(true);
        mTransLayout.setClickable(true);
        mIpAddrTextView.setEnabled(true);
        mIpAddrLayout.setClickable(true);
        mLocalPortLayout.setClickable(true);
        mType = MainActivity.TYPE_TCP_SERVER;
        mTransTextView.setText("TCP");
        mPlayerTextView.setText("服务器端");
    }

    private void showTcpClientView() {
        setAllWidgetInvisible();
        mErrPortLayout.setClickable(true);
        mErrTextView.setEnabled(true);
        mLocalPortLayout.setVisibility(View.GONE);
        mIpTextViewLeft.setText("IP地址");
        mPlayerLayout.setVisibility(View.VISIBLE);
        mPlayerLayout.setClickable(true);
        mTransLayout.setClickable(true);
        mIpAddrTextView.setEnabled(true);
        mPortTextView.setEnabled(true);
        mIpAddrLayout.setClickable(true);
        mWorkPortLayout.setVisibility(View.VISIBLE);
        mWorkPortLayout.setClickable(true);
        mType = MainActivity.TYPE_TCP_CLIENT;
        mTransTextView.setText("TCP");
        mPlayerTextView.setText("客户端");
    }

    private void showUdpView() {
        setAllWidgetInvisible();
        mErrPortLayout.setClickable(true);
        mErrTextView.setEnabled(true);
        mLocalPortLayout.setVisibility(View.VISIBLE);
        mIpTextViewLeft.setText("IP地址");
        mPlayerLayout.setVisibility(View.GONE);
        mTransLayout.setClickable(true);
        mLocalPortTextView.setEnabled(true);
        mIpAddrTextView.setEnabled(true);
        mPortTextView.setEnabled(true);
        mWorkPortLayout.setVisibility(View.VISIBLE);
        mLocalPortLayout.setClickable(true);
        mIpAddrLayout.setClickable(true);
        mWorkPortLayout.setClickable(true);
        mType = MainActivity.TYPE_UDP;
        mTransTextView.setText("UDP");
        mPlayerTextView.setText("服务器端");
    }

    private void clickTransLayout() {
        if (mType != MainActivity.TYPE_UDP) {
            showUdpView();
        } else {
            showTcpServerView();
        }
    }

    private void clickPlayerLayout() {
        if (mType == MainActivity.TYPE_TCP_SERVER) {
            showTcpClientView();
        } else {
            showTcpServerView();
        }
    }

    private void clickConnectLayout() {
        if (!mConnected) {
            mConnecTextView.setText("连接中...");
            mConnecTextView.setTextColor(mActivity.getResources().getColor(
                    R.color.red));
            mConnLayout.setClickable(false);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Message msg = new Message();
                    msg.what = CNN_CONNECT;
                    mCnnHandler.sendMessage(msg);
                }
            });
            thread.start();
        } else {
            mConnecTextView.setText("断开中...");
            mConnecTextView.setTextColor(mActivity.getResources().getColor(
                    R.color.red));
            mConnLayout.setClickable(false);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Message msg = new Message();
                    msg.what = CNN_UNCONNECT;
                    mCnnHandler.sendMessage(msg);
                }
            });
            thread.start();
        }
    }

    private class LayoutOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.RelativeLayouttrans:
                    clickTransLayout();
                    break;
                case R.id.RelativeLayoutplay:
                    clickPlayerLayout();
                    break;
                case R.id.RelativeLayoutconnect:
                    if (System.currentTimeMillis() - mTimeCount >= 2000) {
                        clickConnectLayout();
                        mTimeCount = System.currentTimeMillis();
                    }
                    break;
                case R.id.RelativeLayoutlocalport:
                    mPortAlertDialog = new PortAlertDialog(mActivity,
                            mActivity.getLayoutInflater());
                    mPortAlertDialog.setPositiveButton("确定",
                            new AlertDialogPositiveClickListener(0));
                    mPortAlertDialog.setTitle("本机端口");
                    mPortAlertDialog.setPort(mLocalPort);
                    mPortAlertDialog.show();
                    break;
                case R.id.RelativeLayoutip:
                    mIpAlertDialog = new IpAlertDialog(mActivity,
                            mActivity.getLayoutInflater());
                    mIpAlertDialog.setPositiveButton("确定",
                            new AlertDialogPositiveClickListener(1));
                    mIpAlertDialog.setIp(mIpAddr);
                    mIpAlertDialog.show();
                    break;
                case R.id.RelativeLayoutworkport:
                    mPortAlertDialog = new PortAlertDialog(mActivity,
                            mActivity.getLayoutInflater());
                    mPortAlertDialog.setPositiveButton("确定",
                            new AlertDialogPositiveClickListener(2));
                    mPortAlertDialog.setTitle("工作端口");
                    mPortAlertDialog.setPort(mWorkPort);
                    mPortAlertDialog.show();
                    break;
                case R.id.RelativeLayoutErrPort:
                    mPortAlertDialog = new PortAlertDialog(mActivity,
                            mActivity.getLayoutInflater());
                    mPortAlertDialog.setPositiveButton("确定",
                            new AlertDialogPositiveClickListener(3));
                    mPortAlertDialog.setTitle("错误通知端口");
                    mPortAlertDialog.setPort(mErrPort);
                    mPortAlertDialog.show();
                    break;
                default:
                    break;
            }
        }

    }

    private class AlertDialogPositiveClickListener implements
            DialogInterface.OnClickListener {

        private int mIndex;

        public AlertDialogPositiveClickListener(int nIndex) {
            mIndex = nIndex;
        }

        @Override
        public void onClick(DialogInterface di, int arg1) {
            // TODO Auto-generated method stub
            switch (mIndex) {
                case 0:
                    mPortAlertDialog.Invalidate();
                    mLocalPort = mPortAlertDialog.getPort();
                    mLocalPortTextView.setText(mLocalPort + "");
                    break;
                case 1:
                    mIpAlertDialog.Invalidate();
                    mIpAddr = mIpAlertDialog.getIp();
                    mIpAddrTextView.setText(mIpAddr);
                    break;
                case 2:
                    mPortAlertDialog.Invalidate();
                    mWorkPort = mPortAlertDialog.getPort();
                    mPortTextView.setText(mWorkPort + "");
                    break;
                case 3:
                    mPortAlertDialog.Invalidate();
                    mErrPort = mPortAlertDialog.getPort();
                    mErrTextView.setText(mErrPort + "");
                    break;
                default:
                    break;
            }
            di.dismiss();
        }
    }

    @SuppressLint("HandlerLeak")
    private class CnnHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case CNN_CONNECT:
                    connect();
                    break;
                case CNN_UNCONNECT:
                    unconnect();
                    break;
            }
        }
    }
}
